package com.atguigu.guli.service.cms.service.impl;

import com.atguigu.guli.service.cms.entity.Ad;
import com.atguigu.guli.service.cms.mapper.AdMapper;
import com.atguigu.guli.service.cms.service.AdService;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 广告推荐 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2021-07-07
 */
@Service
public class AdServiceImpl extends ServiceImpl<AdMapper, Ad> implements AdService {

    @Autowired
    private AdMapper adMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    //查询所有的广告
    @Cacheable(value ="ads"  ,key = "'hotads'")  // 自动缓存
    @Override
    public Map getAdAll() {
        //redisTemplate 存储自定义类型的对象时，自定义类需要实现序列化接口
        /*Object adsMap = redisTemplate.opsForValue().get("ads");
        if (adsMap!= null) {
            return (Map) adsMap;
        }*/

        Map map = new HashMap();

        QueryWrapper<Ad> queryWrapper = new QueryWrapper<>();
        // queryWrapper.orderByDesc("type_id");  // 根据type_id升序
        // queryWrapper.orderByAsc("type_id");

        queryWrapper.orderByDesc("gmt_modified");  // 根据修改时间降序
        queryWrapper.orderByDesc("sort");  // 根据sort降序

        List<Ad> ads = adMapper.selectList(queryWrapper);

        List<Ad> banners = new ArrayList<>();
        List<Ad> teachers = new ArrayList<>();
        List<Ad> courses = new ArrayList<>();

        // 根据typeId 判断广告类型
        for (Ad ad : ads) {
            if ("1".equals(ad.getTypeId())) {
                banners.add(ad);
            } else if ("2".equals(ad.getTypeId())) {
                teachers.add(ad);
            } else if ("3".equals(ad.getTypeId())) {
                courses.add(ad);
            }
        }

        map.put("courses", courses);
        map.put("teachers", teachers);
        map.put("banners", banners);

        // 将热门数据保存到 redis 中
        // redisTemplate.opsForValue().set("ads", map, 60, TimeUnit.MINUTES);

        return map;
    }
}
